package com.itboye.zhujia.base;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.itboye.zhujia.R;
import com.itboye.zhujia.bean.ResultEntity;
import com.itboye.zhujia.util.ByAlert;
import com.itboye.zhujia.util.DensityUtil;
import com.itboye.zhujia.util.LoadingDialog;
import com.umeng.analytics.MobclickAgent;

/**
 * @author hebidu 2016-4-25 wushunhui修改版
 *         继承该类不需要自己寻找控件，不需要自己写oncreate(),只需要重写里面的抽象方法即可
 */
@SuppressLint("NewApi")
public abstract class BaseActivity extends FragmentActivity {

	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
			.getName() + "_unknown";
	View statusBar;
	LoadingDialog progressDialog = null;
//	private PushAgent mPushAgent;
	private LinearLayout container;
	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		setContentView(initView());// 设置布局
		progressDialog = new LoadingDialog();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//			Window window = getWindow();
//			// Translucent status bar
//			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//			statusBar = new View(this);
//			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
//					ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight());
//			statusBar.setLayoutParams(param);
			// setStatusBarColor(R.color.main_color);
//			this.addContentView(statusBar, param);
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

			statusBar = new View(this);
			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					getStatusBarHeight());
			statusBar.setLayoutParams(param);
//			setStatusBarColor(R.color.orange);
			  container =new ViewContainer(getApplicationContext());
				container.setOrientation(LinearLayout.VERTICAL);
				container.addView(statusBar);
			// App.getInstance().addActivity(this);

		}
		// 判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
//		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//		}
//		mPushAgent=PushAgent.getInstance(this);
//		mPushAgent.onAppStart();//推送开始
		smartInject();// 自动获取控件
		onMyCreate();

	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	protected int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height",
				"dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	/**
	 * @param data
	 * @return 2016-4-23 hebidu
	 */
	public ResultEntity handlerError(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {
			ByAlert.alert(result.getMsg());
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}

	/**
	 * 设置状态栏颜色，
	 * 
	 * @param color
	 *            颜色资源id， 如 R.color.orange</br> 0 黑色
	 */
	protected void setStatusBarColor(int color) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (color == 0) {
				statusBar.setBackgroundColor(Color.BLACK);
			} else {
				statusBar.setBackgroundColor(getResources().getColor(color));
			}

		}
	}

	/**
	 * @param 2016-4-25 wushunhui
	 */
	private void smartInject() {

		try {
			Class<? extends Activity> clz = getClass();

			while (clz != BaseActivity.class) {

				Field[] fs = clz.getDeclaredFields();
				Resources res = getResources();
				String packageName = getPackageName();
				System.out.println("packageName" + packageName);
				for (Field field : fs) {

					System.out.println("field.getType()" + field.getType());
					if (!View.class.isAssignableFrom(field.getType())) {
						continue;
					}
					System.out.println("field.getName()" + field.getName());

					int viewId = res.getIdentifier(field.getName(), "id",
							packageName);
					System.out.println("viewId" + viewId);
					if (viewId == 0)
						continue;
					field.setAccessible(true);
					try {
						View v = findViewById(viewId);
						field.set(this, v);
						Class<?> c = field.getType();
						Method m = c.getMethod("setOnClickListener",
								android.view.View.OnClickListener.class);
						m.invoke(v, this);
					} catch (Throwable e) {
					}
					field.setAccessible(false);

				}

				clz = (Class<? extends Activity>) clz.getSuperclass();

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @author liutiantian 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		String vsersionNmae = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;

			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}

	/***
	 * 所有继承BaseActivity所要调用的方法
	 * 
	 * @return
	 */
	public abstract int initView();// 初始化控件及其他

	public abstract void onMyCreate();// 初始化数据相当于oncreate

	/**
	 * 显示进度对话框,带有消息 flag 是否可以取消
	 */
	@SuppressLint("NewApi")
	public void showProgressDialog(String message, boolean flag) {
		if (progressDialog == null)
			return;
		setProgressDialogMessage(message);

		progressDialog.show(getFragmentManager(), message);
		progressDialog.setCancelable(flag);

	}
	
	@Override
	public void setContentView(@LayoutRes int layoutResID) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			
			LayoutInflater.from(this).inflate(layoutResID, container, true);
			setContentView(container);
		}else{
			setContentView(layoutResID);
		}
		smartInject();
//		FrameLayout container = new FrameLayout(this);
//		// 在用户布局外面嵌套一个FrameLayout，防止用户布局中根控件的margin失效
//		LayoutInflater.from(this).inflate(layoutResID, container, true);
//		setContentView(container);

	}

	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMsg(message);
	}

	/**
	 * 关闭进度对话框
	 */
	@SuppressLint("NewApi")
	public void closeProgressDialog() {
		if (progressDialog != null) {
			if (progressDialog.getDialog().isShowing()) {
				progressDialog.dismiss();
			}
		}
	}
	/**
	 * 是否开启  右划关闭activity 手势，默认开启
	 */
	private boolean isGestureOpen=true;
	/**
	 * 屏幕左侧右划返回容器 , 
	 * @author Young
	 *
	 */
	private class ViewContainer extends LinearLayout{

		private int leftMargin;
		private VelocityTracker tracker;
		private float startX;
		private float startY;
		public ViewContainer(Context context) {
			super(context);
			leftMargin=DensityUtil.dip2px(35);
			
		}
		
		@Override
		public boolean dispatchTouchEvent(MotionEvent ev) {
			if (isGestureOpen==false) {
				return super.dispatchTouchEvent(ev);
			}
			switch (ev.getAction()) {
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				//当满足下面条件时 视为 右划关闭手势  
				//起始按压位置x坐标小与leftMargin&& 向右滑动                       &&           向右滑动距离    >   竖直方向距离 
				if (startX<leftMargin&& ev.getRawX()>startX && ev.getRawX()-startX>Math.abs(ev.getRawY()-startY) ) {
					//速度大于2500时关闭activity
					tracker.computeCurrentVelocity(1000);
					 if (tracker.getXVelocity()>2500) {
						finish();
					}
					
				}
				 
				tracker.recycle();
				break;

			case MotionEvent.ACTION_DOWN:
				startX=ev.getRawX();
				startY=ev.getRawY();
				tracker=VelocityTracker.obtain();
				tracker.addMovement(ev);
				break;
			case MotionEvent.ACTION_MOVE:
				tracker.addMovement(ev);
				break;
			}
			
			 
			return super.dispatchTouchEvent(ev);
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			if (isGestureOpen==false) {
				return super.onTouchEvent(event);
			}
			return true;
		}
		
	}

}
